package 开始的剑指offer8月.面经常用算法题09开始的;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
// https://leetcode-cn.com/problems/majority-element/solution/3chong-fang-fa-by-gfu-2/
public class 算法面试题169多数元素0906 {
    private static Map<Integer, Integer> countNums(int[] nums) {
        Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
        for (int num : nums) {
            if (!counts.containsKey(num)) {
                counts.put(num, 1);
            } else {
                counts.put(num, counts.get(num) + 1);
            }
        }
        return counts;
    }

    public static int majorityElement(int[] nums) {
        Map<Integer, Integer> counts = countNums(nums);

        Map.Entry<Integer, Integer> majorityEntry = null;
        for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
            if (majorityEntry == null || entry.getValue() > majorityEntry.getValue()) {
                majorityEntry = entry;
            }
        }

        return majorityEntry.getKey();
    }

    public static int majorityElement1(int[] nums) {
        Arrays.sort(nums);
        System.out.println(nums[1]);
        return nums[nums.length >> 1];
    }

    public static void main(String[] args) {
        System.out.println(majorityElement(new int[]{3,2,3}));
        System.out.println(majorityElement1(new int[]{3,2,3}));
    }
}
